package cn.dckeji.dcssm.service.impl;

import cn.dckeji.dcssm.common.utils.MD5Util;
import cn.dckeji.dcssm.dao.AdminDao;
import cn.dckeji.dcssm.entity.Admin;
import cn.dckeji.dcssm.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 后台管理员表 服务实现类
 * </p>
 *
 * @author Kenny
 * @since 2019-02-21
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements AdminService {

    @Resource
    private AdminDao adminDao;

    @Override
    public void updateLoginPassword(Admin admin) {
        adminDao.updateById(admin);
    }

    @Override
    public void updateAdminPassword(String adminId) {
        Admin admin = adminDao.selectById(adminId);
        admin.setLoginPassword(MD5Util.MD5Encode("123456", "utf-8"));
        admin.setGmtModified(LocalDateTime.now());
        adminDao.updateById(admin);
    }

    @Override
    public boolean saveAdmin(Admin admin) {
        //查询登录名重复没
        String adminId = admin.getId();
        String loginName = admin.getLoginName();
        Admin dataAdmin = adminDao.selectOne(new QueryWrapper<Admin>().eq("login_name", loginName));
        if (dataAdmin!=null) {
            if (StringUtils.isNotBlank(adminId)) {
                String dataAdminId = dataAdmin.getId();
                if (dataAdminId.equals(adminId)) {
                    dataAdmin.setRemark(admin.getRemark());
                    dataAdmin.setRoleId(admin.getRoleId());
                    dataAdmin.setGmtModified(LocalDateTime.now());
                    adminDao.updateById(dataAdmin);
                    return true;
                }
            }
        }else {
            if (StringUtils.isNotBlank(adminId)) {
                admin.setGmtModified(LocalDateTime.now());
                adminDao.updateById(admin);
            }else {
                admin.setLoginPassword(MD5Util.MD5Encode(admin.getLoginPassword(),"utf-8"));
                admin.setGmtCreate(LocalDateTime.now());
                adminDao.insert(admin);
            }
            return true;
        }
        return false;
    }
}
